/*
 * Convert BDF files to C source and/or Rockbox .fnt file format
 *
 * Copyright 2002 by Greg Haerr <greg@censoft.com>
 *
 * What fun it is converting font data...
 *
 * 09/17/02	Version 1.0
 * 01/28/07 Kenny Chen Modified Version 1.0
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>

#include <config.h>

#ifdef FONT_BDF_SUPPORT

#include <systems.h>
#include <types.h>
#include <misc.h>
#include <font_bdf.h>

#define isprefix(buf,str)	(!strncmp(buf, str, strlen(str)))
#define	strequal(s1,s2)		(!strcmp(s1, s2))

#define EXTRA	300		/* # bytes extra allocation for buggy .bdf files*/

int gen_c = 0;
int gen_fnt = 0;
int gen_map = 1;
int start_char = 0;
int limit_char = 65535;
int oflag = 0;
char outfile[256];

/* free font structure*/
void bdf_free_font(BDF_FONT * pf)
{
    if (!pf)
        return;
    if (pf->name)
        free(pf->name);
    if (pf->facename)
        free(pf->facename);
    if (pf->bits)
        free(pf->bits);
    if (pf->offset)
        free(pf->offset);
    if (pf->width)
        free(pf->width);
    free(pf);
}

/* build incore structure from .bdf file*/
BDF_FONT * bdf_read_font(char *path)
{
    FILE *fp;
    BDF_FONT * pf;

    fp = fopen(path, "rb");
    if (!fp) {
        ERROR("Error opening file: %s\n", path);
        return NULL;
    }

    pf = (BDF_FONT *)calloc(1, sizeof(BDF_FONT));
    if (!pf)
        goto errout;
    
    pf->name = strdup(_basename(path));

    if (!bdf_read_header(fp, pf)) {
        ERROR("Error reading font header\n");
        goto errout;
    }

    if (!bdf_read_bitmaps(fp, pf)) {
        ERROR("Error reading font bitmaps\n");
        goto errout;
    }

    fclose(fp);
    return pf;

errout:
    fclose(fp);
    free_font(pf);
    return NULL;
}

/* read bdf font header information, return 0 on error*/
int bdf_read_header(FILE *fp, BDF_FONT * pf)
{
    int encoding;
    int nchars, maxwidth;
    int firstchar = 65535;
    int lastchar = -1;
    char buf[256];
    char facename[256];
    char copyright[256];

    /* set certain values to errors for later error checking*/
    pf->defaultchar = -1;
    pf->ascent = -1;
    pf->descent = -1;

    for (;;) {
        if (!bdf_getline(fp, buf, sizeof(buf))) {
            ERROR("Error: EOF on file\n");
            return 0;
        }
        if (isprefix(buf, "FONT ")) {        /* not required*/
            if (sscanf(buf, "FONT %[^\n]", facename) != 1) {
                ERROR("Error: bad 'FONT'\n");
                return 0;
            }
            pf->facename = strdup(facename);
            continue;
        }
        if (isprefix(buf, "COPYRIGHT ")) {    /* not required*/
            if (sscanf(buf, "COPYRIGHT \"%[^\"]", copyright) != 1) {
                ERROR("Error: bad 'COPYRIGHT'\n");
                return 0;
            }
            pf->copyright = strdup(copyright);
            continue;
        }
        if (isprefix(buf, "DEFAULT_CHAR ")) {    /* not required*/
            if (sscanf(buf, "DEFAULT_CHAR %d", &pf->defaultchar) != 1) {
                ERROR("Error: bad 'DEFAULT_CHAR'\n");
                return 0;
            }
        }
        if (isprefix(buf, "FONT_DESCENT ")) {
            if (sscanf(buf, "FONT_DESCENT %d", &pf->descent) != 1) {
                ERROR("Error: bad 'FONT_DESCENT'\n");
                return 0;
            }
            continue;
        }
        if (isprefix(buf, "FONT_ASCENT ")) {
            if (sscanf(buf, "FONT_ASCENT %d", &pf->ascent) != 1) {
                ERROR("Error: bad 'FONT_ASCENT'\n");
                return 0;
            }
            continue;
        }
        if (isprefix(buf, "FONTBOUNDINGBOX ")) {
            if (sscanf(buf, "FONTBOUNDINGBOX %d %d %d %d",
                &pf->fbbw, &pf->fbbh, &pf->fbbx, &pf->fbby) != 4) {
                ERROR("Error: bad 'FONTBOUNDINGBOX'\n");
                return 0;
            }
            continue;
        }
        if (isprefix(buf, "CHARS ")) {
            if (sscanf(buf, "CHARS %d", &nchars) != 1) {
                ERROR("Error: bad 'CHARS'\n");
                return 0;
            }
            continue;
        }

        /*
         * Reading ENCODING is necessary to get firstchar/lastchar
         * which is needed to pre-calculate our offset and widths
         * array sizes.
         */
        if (isprefix(buf, "ENCODING ")) {
            if (sscanf(buf, "ENCODING %d", &encoding) != 1) {
                ERROR("Error: bad 'ENCODING'\n");
                return 0;
            }
            if (encoding >= 0 && encoding <= limit_char && encoding >= start_char) {
                if (firstchar > encoding)
                    firstchar = encoding;
                if (lastchar < encoding)
                    lastchar = encoding;
            }
            continue;
        }
        if (strequal(buf, "ENDFONT"))
            break;
    }

    /* calc font height*/
    if (pf->ascent < 0 || pf->descent < 0 || firstchar < 0) {
        ERROR("Error: Invalid BDF file, requires FONT_ASCENT/FONT_DESCENT/ENCODING\n");
        return 0;
    }
    pf->height = pf->ascent + pf->descent;

    /* calc default char*/
    if (pf->defaultchar < 0 || pf->defaultchar < firstchar ||
        pf->defaultchar > limit_char)
        pf->defaultchar = firstchar;

    /* calc font size (offset/width entries)*/
    pf->firstchar = firstchar;
    pf->size = lastchar - firstchar + 1;
    
    /* use the font boundingbox to get initial maxwidth*/
    /*maxwidth = pf->fbbw - pf->fbbx;*/
    maxwidth = pf->fbbw;

    /* initially use font maxwidth * height for bits allocation*/
    pf->bits_size = nchars * MWIMAGE_WORDS(maxwidth) * pf->height;

    /* allocate bits, offset, and width arrays*/
    pf->bits = (MWIMAGEBITS *)malloc(pf->bits_size * sizeof(MWIMAGEBITS) + EXTRA);
    pf->offset = (unsigned long *)malloc(pf->size * sizeof(unsigned long));
    pf->width = (unsigned char *)malloc(pf->size * sizeof(unsigned char));
    
    if (!pf->bits || !pf->offset || !pf->width) {
        ERROR("Error: no memory for font load\n");
        return 0;
    }

    return 1;
}

/* read bdf font bitmaps, return 0 on error*/
int bdf_read_bitmaps(FILE *fp, BDF_FONT * pf)
{
    long ofs = 0;
    int maxwidth = 0;
    int i, k, encoding, width;
    int bbw, bbh, bbx, bby;
    int proportional = 0;
    int encodetable = 0;
    long l;
    char buf[256];

    /* reset file pointer*/
    fseek(fp, 0L, SEEK_SET);

    /* initially mark offsets as not used*/
    for (i=0; i<pf->size; ++i)
        pf->offset[i] = -1;

    for (;;) {
        if (!bdf_getline(fp, buf, sizeof(buf))) {
            ERROR("Error: EOF on file\n");
            return 0;
        }
        if (isprefix(buf, "STARTCHAR")) {
            encoding = width = bbw = bbh = bbx = bby = -1;
            continue;
        }
        if (isprefix(buf, "ENCODING ")) {
            if (sscanf(buf, "ENCODING %d", &encoding) != 1) {
                ERROR("Error: bad 'ENCODING'\n");
                return 0;
            }
            if (encoding < start_char || encoding > limit_char)
                encoding = -1;
            continue;
        }
        if (isprefix(buf, "DWIDTH ")) {
            if (sscanf(buf, "DWIDTH %d", &width) != 1) {
                ERROR("Error: bad 'DWIDTH'\n");
                return 0;
            }
            /* use font boundingbox width if DWIDTH <= 0*/
            if (width <= 0)
                width = pf->fbbw - pf->fbbx;
            continue;
        }
        if (isprefix(buf, "BBX ")) {
            if (sscanf(buf, "BBX %d %d %d %d", &bbw, &bbh, &bbx, &bby) != 4) {
                ERROR("Error: bad 'BBX'\n");
                return 0;
            }
            continue;
        }
        if (strequal(buf, "BITMAP")) {
            MWIMAGEBITS *ch_bitmap = pf->bits + ofs;
            int ch_words;

            if (encoding < 0)
                continue;

            /* set bits offset in encode map*/
            if (pf->offset[encoding-pf->firstchar] != (unsigned long)-1) {
                ERROR("Error: duplicate encoding for character %d (0x%02x), ignoring duplicate\n",
                    encoding, encoding);
                continue;
            }
            pf->offset[encoding-pf->firstchar] = ofs;

            /* calc char width*/
            if (bbx < 0) {
                width -= bbx;
                /*if (width > maxwidth)
                    width = maxwidth;*/
                bbx = 0;
            }
            if (width > maxwidth)
                maxwidth = width;
            pf->width[encoding-pf->firstchar] = width;

            /* clear bitmap*/
            memset(ch_bitmap, 0, MWIMAGE_BYTES(width) * pf->height);

            ch_words = MWIMAGE_WORDS(width);
#define BM(row,col)    (*(ch_bitmap + ((row)*ch_words) + (col)))
#define MWIMAGE_NIBBLES    (MWIMAGE_BITSPERIMAGE/4)

            /* read bitmaps*/
            for (i=0; ; ++i) {
                int hexnibbles;

                if (!bdf_getline(fp, buf, sizeof(buf))) {
                    ERROR("Error: EOF reading BITMAP data\n");
                    return 0;
                }
                if (isprefix(buf, "ENDCHAR"))
                    break;

                hexnibbles = strlen(buf);
                for (k=0; k<ch_words; ++k) {
                    int ndx = k * MWIMAGE_NIBBLES;
                    int padnibbles = hexnibbles - ndx;
                    MWIMAGEBITS value;
                    
                    if (padnibbles <= 0)
                        break;
                    if (padnibbles >= MWIMAGE_NIBBLES)
                        padnibbles = 0;

                    value = bdf_hexval((unsigned char *)buf,
                        ndx, ndx+MWIMAGE_NIBBLES-1-padnibbles);
                    value <<= padnibbles * MWIMAGE_NIBBLES;

                    BM(pf->height - pf->descent - bby - bbh + i, k) |=
                        value >> bbx;
                    /* handle overflow into next image word*/
                    if (bbx) {
                        BM(pf->height - pf->descent - bby - bbh + i, k+1) =
                            value << (MWIMAGE_BITSPERIMAGE - bbx);
                    }
                }
            }

            ofs += MWIMAGE_WORDS(width) * pf->height;

            continue;
        }
        if (strequal(buf, "ENDFONT"))
            break;
    }

    /* set max width*/
    pf->maxwidth = maxwidth;

    /* change unused offset/width values to default char values*/
    for (i=0; i<pf->size; ++i) {
        int defchar = pf->defaultchar - pf->firstchar;

        if (pf->offset[i] == (unsigned long)-1) {
            pf->offset[i] = pf->offset[defchar];
            pf->width[i] = pf->width[defchar];
        }
    }

    /* determine whether font doesn't require encode table*/
    l = 0;
    for (i=0; i<pf->size; ++i) {
        if (pf->offset[i] != l) {
            encodetable = 1;
            break;
        }
        l += MWIMAGE_WORDS(pf->width[i]) * pf->height;
    }
    if (!encodetable) {
        free(pf->offset);
        pf->offset = NULL;
    }

    /* determine whether font is fixed-width*/
    for (i=0; i<pf->size; ++i) {
        if (pf->width[i] != maxwidth) {
            proportional = 1;
            break;
        }
    }
    if (!proportional) {
        free(pf->width);
        pf->width = NULL;
    }

    /* reallocate bits array to actual bits used*/
    if (ofs < pf->bits_size) {
        pf->bits = realloc(pf->bits, ofs * sizeof(MWIMAGEBITS));
        pf->bits_size = ofs;
    } else if (ofs > pf->bits_size) {
        WARNING("DWIDTH spec > max FONTBOUNDINGBOX\n");
        if (ofs > pf->bits_size+EXTRA) {
            ERROR("Error: Not enough bits initially allocated\n");
            return 0;
        }
        pf->bits_size = ofs;
    }

    return 1;
}

/* read the next non-comment line, returns buf or NULL if EOF*/
char *bdf_getline(FILE *fp, char *buf, int len)
{
    int c;
    char *b;

    for (;;) {
        b = buf;
        while ((c = getc(fp)) != EOF) {
            if (c == '\r')
                continue;
            if (c == '\n')
                break;
            if (b - buf >= (len - 1))
                break;
            *b++ = c;
        }
        *b = '\0';
        if (c == EOF && b == buf)
            return NULL;
        if (b != buf && !isprefix(buf, "COMMENT"))
            break;
    }
    return buf;
}

/* return hex value of portion of buffer*/
MWIMAGEBITS bdf_hexval(unsigned char *buf, int ndx1, int ndx2)
{
    MWIMAGEBITS val = 0;
    int i, c;

    for (i=ndx1; i<=ndx2; ++i) {
        c = buf[i];
        if (c >= '0' && c <= '9')
            c -= '0';
        else if (c >= 'A' && c <= 'F')
            c = c - 'A' + 10;
        else if (c >= 'a' && c <= 'f')
            c = c - 'a' + 10;
        else c = 0;
        val = (val << 4) | c;
    }
    return val;
}

/*
Font information:
    name:         pf->name
    facename:     pf->facename
    w x h:        pf->maxwidth, pf->height
    size:         pf->size
    ascent:       pf->ascent
    descent:      pf->descent
    first char:   pf->firstchar
    last char:    pf->firstchar+pf->size-1
    default char: pf->defaultchar
    proportional: pf->copyright
*/
u8 *bdf_load_bmp(BDF_FONT * pf, u32 code, COLOR *bg, COLOR *fg)
{
    int x, y, i, width, height, bitcount = 0;
    MWIMAGEBITS *bits, *ofs, bitvalue = 0;
    u8 *bmp;
#if defined(CS_RGB565)
    u16 color;
#elif defined(CS_RGB888)
    u8 color;
#endif
    COLOR def_bg = {0, 0, 0};
    COLOR def_fg = {0xff, 0xff, 0xff};
    char red, green, blue;

    ofs = pf->bits;
    i = code - pf->firstchar;
     width = pf->width ? pf->width[i] : pf->maxwidth;
    height = pf->height;
    bits = pf->bits + (pf->offset? pf->offset[i]: (height * i));

#if defined(CS_RGB565)
    bmp = malloc((width * height) * 2);
#elif defined(CS_RGB888)
    bmp = malloc((width * height) * 3);
#endif

    if(bmp == NULL)
    {
    ERROR("Error allocating memory for font %s.\n", pf->name);
    return NULL;
    }
  
    if(!bg)    bg = &def_bg;
    if(!fg)    fg = &def_fg;
      
    DPRINTF("Character %d (0x%02x):   width %d\n", 
             i+pf->firstchar, i+pf->firstchar, width);

    x = 0;
    y = 0;
    while (height > 0) {
        if (bitcount <= 0) {
            bitcount = MWIMAGE_BITSPERIMAGE;
            bitvalue = *bits++;
        }

        if(MWIMAGE_TESTBIT(bitvalue)) {
            red = fg->r;
            green = fg->g;
            blue = fg->b;
        }
        else {
            red = bg->r;
            green = bg->g;
            blue = bg->b;
        }
        
#if defined(CS_RGB565)  
#if defined(NIOS2_COLOR_TRANSFORM_SUPPORT)
    color = (u16)CT_RGB2RGB565(red, green, blue);
#else
    color = RGB2PIXEL565(red, green, blue);
#endif
    ((u16 *)bmp)[x + y * width] = color;
#elif defined(CS_RGB888)
    ((u8 *)bmp)[x + (x << 1) + y * width] = red;
    ((u8 *)bmp)[x + (x << 1) + 1 + y * width] = green;
    ((u8 *)bmp)[x + (x << 1) + 2 + y * width] = blue;
#endif

        bitvalue = MWIMAGE_SHIFTBIT(bitvalue);
        --bitcount;
        if (++x == width) {
            --height;
            y = pf->height - height;
            x = 0;
            bitcount = 0;
        }
    }
    
    if(bg == &def_bg)    bg = NULL;
    if(fg == &def_fg)    fg = NULL;
  
    return bmp;
}

#if 0
static int WRITEBYTE(FILE *fp, unsigned char c)
{
    return putc(c, fp) != EOF;
}

static int WRITESHORT(FILE *fp, unsigned short s)
{
    putc(s, fp);
    return putc(s>>8, fp) != EOF;
}

static int WRITELONG(FILE *fp, unsigned long l)
{
    putc(l, fp);
    putc(l>>8, fp);
    putc(l>>16, fp);
    return putc(l>>24, fp) != EOF;
}

static int WRITESTR(FILE *fp, char *str, int count)
{
    return fwrite(str, 1, count, fp) == count;
}

static int WRITESTRPAD(FILE *fp, char *str, int totlen)
{
    int ret;
    
    while (str && *str && totlen > 0)
        if (*str) {
            ret = putc(*str++, fp);
            --totlen;
        }
    while (--totlen >= 0)
        ret = putc(' ', fp);
    return ret;
}
#endif

#endif /* FONT_BDF_SUPPORT */
